package com.yuzi.yuziclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yuzi.yuziclientsdk.model.User;
import com.yuzi.yuziclientsdk.utils.signUtils;

import java.util.HashMap;
import java.util.Map;

public class YuziClient {

    //计算签名sign
    private String accessKey;
    private String secretKey;

    private static final String GATEWAY_HOST = "http://localhost:8090";

    public YuziClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private Map<String, String> getHeads(String body) {
        Map<String, String> headers = new HashMap<>();
        headers.put("accessKey", accessKey);
        //放入密钥可能会被拦截
        //headers.put("secretKey",secretKey);
        //用户输入的参数
        headers.put("body", body);
        //nonce随机数 只能用一次
        headers.put("nonce", RandomUtil.randomNumbers(4));
        //timestamp时间戳 校验它的有效期
        headers.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        headers.put("sign", signUtils.getSign(body, secretKey));
        return headers;
    }


    //get请求添加参数进请求头HttpRequest.get.addHeaders
    public String getNameByGet(String name) {
        //GET请求
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GATEWAY_HOST + "/api/user/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        //POST请求
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(GATEWAY_HOST + "/api/user/post", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByJson(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse response = HttpRequest.post(GATEWAY_HOST + "/api/user/json")
                .addHeaders(getHeads(json))
                .body(json)
                .execute();
        String body = response.body();
        System.out.println(body);
        return body;
    }

}
